package com.seata.demo.storage.service.impl;

import com.seata.demo.storage.entity.Storage;
import com.seata.demo.storage.mapper.StorageMapper;
import com.seata.demo.storage.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageMapper storageMapper;

    @Override
    public void deduct(String commodityCode, Integer count) {
        int result = storageMapper.deduct(commodityCode, count);
        if (result <= 0) {
            throw new RuntimeException("库存不足，扣减失败");
        }
    }
    
    @Override
    public void revert(String commodityCode, Integer count) {
        // 实际应用中应该实现具体的库存恢复逻辑
        Storage storage = storageMapper.selectByCommodityCode(commodityCode);
        if (storage != null) {
            // 这里简化处理，实际应根据业务场景实现
        }
    }

    // TCC模式方法
    @Override
    public boolean tryDeduct(String commodityCode, Integer count) {
        // 尝试扣减库存，先冻结
        int result = storageMapper.freeze(commodityCode, count);
        return result > 0;
    }

    @Override
    public boolean confirmDeduct(String commodityCode, Integer count) {
        // 确认扣减，将冻结的库存实际扣除
        int result = storageMapper.confirmDeduct(commodityCode, count);
        return result > 0;
    }

    @Override
    public boolean cancelDeduct(String commodityCode, Integer count) {
        // 取消扣减，解冻库存
        int result = storageMapper.unfreeze(commodityCode, count);
        return result > 0;
    }
}
